<!-- 
    JS实现单例设计模式：
        一个类限制必须只能有一个实例，如果第二次创建的时候，
        我们可以抛出错误或者返回第一次的实例。
 -->

<!-- <script>
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    let malu = new Person("码路", 17); // 码路
    let manman = new Person("漫漫", 15); // 漫漫
    console.log(malu);
    console.log(manman);
</script> -->

<!-- <script>
    let Person = (function () {
        let instance = null;
        return function (name, age) {
            this.name = name;
            this.age = age;
            if (instance) {
                return instance;
            }
            return instance = this;
        }
    })();
    Person.prototype.sayHello = function () {
        console.log(this.name);
    }
    let malu = new Person("码路", 17); // 码路
    let manman = new Person("漫漫", 15); // 漫漫
    console.log(malu);
    console.log(manman);
    console.log(malu === manman);
    malu.sayHello();
    manman.sayHello();
</script> -->

<script>
    // new Person并不是单例的
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    Person.prototype.sayHello = function () {
        console.log(this.name);
    }

    // 创建一个代理类，实现单例设计模式
    let PersonProxy = (function () {
        let instance = null;
        return function (name, age) {
            if (instance) {
                return instance;
            }
            return instance = new Person(name, age)
        }
    })()

    let malu = new PersonProxy("码路", 17); // 码路
    let manman = new PersonProxy("漫漫", 15); // 漫漫
    console.log(malu);
    console.log(manman);
    console.log(malu === manman);
    malu.sayHello();
    manman.sayHello();
</script>